package com.eastedu.superise.handler.basic;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eastedu.converter.BasicResourceKnowledgeConverter;
import com.eastedu.manager.BasicResourceManager;
import com.eastedu.model.ktree.KnowledgeNodeDTO;
import com.eastedu.repository.basic.mapper.BasicResourceKnowledgeMapper;
import com.eastedu.repository.basic.po.BasicResourceKnowledgePO;
import com.eastedu.repository.basic.po.BasicResourcePO;
import com.eastedu.repository.ktree.mapper.KnowledgeNodeMapper;
import com.eastedu.superise.handler.AbstractHistoricalDataHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

/**
 * 处理zip格式微课
 * @author zhangzhishuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KnowledgeHistoricalDataHandler extends AbstractHistoricalDataHandler<BasicResourcePO> {

    private final BasicResourceManager basicResourceManager;
    private final KnowledgeNodeMapper knowledgeNodeMapper;
    private final BasicResourceKnowledgeMapper basicResourceKnowledgeMapper;
    private final BasicResourceKnowledgeConverter basicResourceKnowledgeConverter;


    @Override
    protected String getSql() {
        /*
            故事ID：89604
         */
        return "SELECT DISTINCT br.* FROM t_basic_resource br INNER JOIN t_basic_resource_knowledge brk ON br.id = brk.basic_resource_id";
    }

    @Override
    public void callback(BasicResourcePO po) throws SQLException {
        List<BasicResourceKnowledgePO> basicResourceKnowledgeList = this.basicResourceKnowledgeMapper
                .selectList(Wrappers.lambdaQuery(BasicResourceKnowledgePO.class).eq(BasicResourceKnowledgePO::getBasicResourceId, po.getId()));

        basicResourceKnowledgeList.forEach(item -> {
            String knowledgeGuid = item.getKnowledgeId();
            if (StrUtil.isEmpty(knowledgeGuid)) {
                log.info("知识点ID为空，自动跳过");
                return;
            }
            KnowledgeNodeDTO dto = knowledgeNodeMapper.findByGuid(knowledgeGuid);
            if (ObjectUtil.isNull(dto)) {
                log.info("无效知识点，自动跳过");
                return;
            }
            this.basicResourceKnowledgeConverter.update(dto, item);
            this.basicResourceKnowledgeMapper.updateById(item);
        });

        basicResourceManager.updateKnowledgeJsonByResourceId(String.valueOf(po.getId()), basicResourceKnowledgeList);

    }
}
